#!/usr/bin/env python
# _*_ coding: utf-8 _*_
# @Time : 2022/6/12 18:04
# @Author : Violet
# @File : middleware.py
# @desc : 中间件
from fastapi import FastAPI, Request
# from aioredis.exceptions import ConnectionError
# from tortoise.exceptions import DBConnectionError
from core.logger import logger
from utils import resp_500


# ---------------------------------------------美观线-------------------------------------------------------


def register_middleware(app: FastAPI):
    """ 请求拦截与响应拦截 -- https://fastapi.tiangolo.com/tutorial/middleware/ """

    @app.middleware("http")
    async def intercept(request: Request, call_next):
        logger.info(f"访问记录:IP:{request.client.host}-method:{request.method}-url:{request.url}")
        return await call_next(request)  # 返回请求(跳过token)
    # except ConnectionError as e:
    #     logger.error(f'redis连接失败！-- {e}')
    #     return resp_500(msg=f'redis连接失败！')
    # except DBConnectionError as e:
    #     logger.error(f'数据库连接失败！-- {e}')
    #     return resp_500(msg=f'数据库连接失败！')
